#!/bin/sh

# u: 遇到不存在的变量停止
# e: 遇到执行出错的命令停止
# x: 打印要执行的命令
set -ex
cd ${JIANMU_CONTEXT} && pwd

# docker镜像构建
cmd="docker build"
if [ ${JIANMU_DOCKERFILE} ]; then
    cmd="${cmd} -f ${JIANMU_DOCKERFILE}"
fi
if [ "${JIANMU_DOCKER_BUILD_NO_CACHE}" == "true" ]; then
    cmd="${cmd} --no-cache"
fi
for tag in ${JIANMU_DOCKER_BUILD_TAGS}; do
	cmd="${cmd} -t ${tag}"
done
for arg in ${JIANMU_DOCKER_BUILD_ARGS}; do
	cmd="${cmd} --build-arg ${arg}"
done
image_id=`${cmd} .| tail -n 2| sed -n 1p| awk '{print $3}'`
echo "镜像ID为 ${image_id}"
echo "{\"image_id\": \"${image_id}\"}" > /usr/result_file


# docker运行镜像
if [[ "${JIANMU_DOCKER_RUN_IS}" == "true" ]]; then
	cmd="docker run -d"
	if [[ ${JIANMU_DOCKER_RUN_NAME} ]]; then
		# 直接删除忽略出错
		set +e
		docker rm -f ${JIANMU_DOCKER_RUN_NAME}
		# 恢复错误出错
		set -e
		cmd="${cmd} --name ${JIANMU_DOCKER_RUN_NAME}"
	fi
	if [[ ${JIANMU_DOCKER_RUN_PORT_MAPPING} ]]; then 
		cmd="${cmd} -p ${JIANMU_DOCKER_RUN_PORT_MAPPING}"
	fi
	if [[ ${JIANMU_DOCKER_RUN_NETWORK} ]]; then 
		cmd="${cmd} --network ${JIANMU_DOCKER_RUN_NETWORK}"
	fi
	for volume in ${JIANMU_DOCKER_RUN_VOLUMES}; do
		cmd="${cmd} -v ${volume}"
	done
	if [[ ${JIANMU_DOCKER_RUN_IMAGE} ]]; then
		cmd="${cmd} ${JIANMU_DOCKER_RUN_IMAGE}"
	else
		cmd="${cmd} ${image_id}"
	fi
	${cmd}
fi

# 清理镜像
if [[ "${JIANMU_CLEAN_IMAGE}" == "true" ]]; then
	# 直接删除忽略出错
	set +e
	docker rmi -f ${image_id}
	# 恢复错误出错
	set -e
fi
